#!/bin/bash

# @file create-analytic-syslog-config
#
# Copyright (C) Metaswitch Networks 2017
# If license terms are provided to you in a COPYING file in the root directory
# of the source code repository by which you are accessing this code, then
# the license outlined in that COPYING file applies to your use.
# Otherwise no rights are granted except for those provided to you by
# Metaswitch Networks in a separate written agreement.

# This file creates a syslog config file for Sprout's analytics logs.

syslog_conf_file=/etc/rsyslog.d/30-sproutanalytics.conf
temp_file=$(mktemp sproutanalytics.syslog.XXXXXXXX)

. /etc/clearwater/config

if [ -n "$remote_audit_logging_server" ]; then
  # If a remote syslog server is configured for auditing registrations, we need
  # an rsyslog config line for directing the correct syslogs to this server. We
  # use a regex to forward messages that start with the correct tag and are
  # registrations.
  remote_syslog_audit_server_str=":msg, regex, \"<analytics>.*Registration:.*\" @@${remote_audit_logging_server}"
fi

# Add tls setup to the top of the config file if the option is specified
shopt -s nocasematch
if [[ $remote_audit_logging_use_tls == "y" ]]; then
  cat > $temp_file << EOF
\$ActionSendStreamDriver gtls

# Certificate files
\$DefaultNetstreamDriverCAFile /etc/clearwater/ent/rsyslog-ca.crt
\$DefaultNetstreamDriverCertFile /etc/clearwater/ent/rsyslog-client.crt
\$DefaultNetstreamDriverKeyFile /etc/clearwater/ent/rsyslog-client.key

\$ActionSendStreamDriverAuthMode x509/certvalid
\$ActionSendStreamDriverMode 1

EOF
fi
shopt -u nocasematch

cat >> $temp_file << EOF
\$FileCreateMode 0666
\$umask 0000

# Define a template that strips the "<analytics>" tag off the front of it.  This
# actually strips 14 characters off the message because we also strip off the
# leading whitespace that rsyslog adds in order to conform with RFC3164 syslog
# format, but that we don't want.
\$template analytics-format,"%msg:14:$%\r\n"

:msg, contains, "<analytics>" /var/log/sprout/analytics.log;analytics-format
$remote_syslog_audit_server_str
:msg, contains, "<analytics>" stop

\$FileCreateMode 0644
EOF

if ! diff $temp_file $syslog_conf_file > /dev/null 2>&1
then
  # Update the config file.
  mv $temp_file $syslog_conf_file

  # Restart rsyslog to pick up the new config file.
  service rsyslog restart
else
  rm $temp_file
fi
